// RealEstatePageComponent.js
import React from 'react';
import { 
  Typography,
  Button,
  CircularProgress,
  Paper,
  Box
} from '@mui/material';
import HomeIcon from '@mui/icons-material/Home';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import { motion } from 'framer-motion';
import ContactSection from 'components/ui/ContactSection';
import PersonalSection from 'components/ui/PersonalSection';
import OwnerSection from 'components/ui/OwnerSection';
import PropertySection from 'components/ui/PropertySection';
import AdditionalSection from 'components/ui/AdditionalSection';
import SequentialBackgroundIcons from 'components/electrons/SequentialBackgroundIcons';
import PhotoCameraIcon from '@mui/icons-material/PhotoCamera';
import FlashOnIcon from '@mui/icons-material/FlashOn';
import AccountBalanceIcon from '@mui/icons-material/AccountBalance';
import PriceCheckIcon from '@mui/icons-material/PriceCheck';
import { DEFAULT_HOW_OPTIONS } from 'components/ui/Constants';
import useMlsFormSubmissionComplete from './use-mls-form-submission-complete';
import {
  MLS_DB_HOST,
  MLS_DB_NAME,
  MLS_DB_TABLE,
  MLS_DB_USERNAME,
  MLS_DB_PASSWORD
} from 'config/index';
import { LogViewer } from 'utils/use-server';

// === HERO SECTION ===
export const HeroSection = ({ headerTextStyle, subheaderTextStyle }) => (
  <div style={{ width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
    <motion.div
      animate={{ scaleX: [1, -1] }}
      transition={{
        duration: 0.6,
        repeat: Infinity,
        repeatDelay: 0.6,
        ease: "easeInOut"
      }}
    >
      <HomeIcon sx={{ fontSize: 60, color: 'primary.main' }} />
    </motion.div>
    
    <Typography variant="h4" sx={headerTextStyle}>
      Launch Your Property Listing Referral Today
    </Typography>
    <Typography variant="body1" sx={subheaderTextStyle}>
      Discover How Thousands of Homeowners Are Getting Their Properties Noticed by Qualified Buyers' Agents
    </Typography>
  </div>
);

// === FORM SECTIONS ===
// Form Header Section
export const FormHeaderSection = () => (
  <>
    <Typography variant="h6" sx={{ 
      fontSize: '1.1rem', 
      fontWeight: 'bold', 
      mb: 2, 
      textAlign: 'center', 
      color: 'primary.main',
      position: 'relative',
      zIndex: 2
    }}>
      Kickstart Your Commission-Free Home Sale
    </Typography>
  </>
);

// Form Contact Section Wrapper
export const FormContactSection = ({ formData, handleChange, errors, textFieldStyle, sectionHeaderStyle, useSize, howOptions }) => (
  <ContactSection 
    formData={formData}
    handleChange={handleChange}
    errors={errors}
    textFieldStyle={textFieldStyle}
    sectionHeaderStyle={sectionHeaderStyle}
    useSize={useSize}
    howOptions={howOptions}
  />
);

// Form Personal Section Wrapper
export const FormPersonalSection = ({ formData, handleChange, errors, textFieldStyle, sectionHeaderStyle, useSize }) => (
  <PersonalSection 
    formData={formData}
    handleChange={handleChange}
    errors={errors}
    textFieldStyle={textFieldStyle}
    sectionHeaderStyle={sectionHeaderStyle}
    useSize={useSize}
  />
);

// Form Owner Section Wrapper
export const FormOwnerSection = ({ formData, handleChange, errors, textFieldStyle, sectionHeaderStyle, useSize }) => (
  <OwnerSection 
    formData={formData}
    handleChange={handleChange}
    errors={errors}
    textFieldStyle={textFieldStyle}
    sectionHeaderStyle={sectionHeaderStyle}
    useSize={useSize}
  />
);

// Form Property Section Wrapper
export const FormPropertySection = ({ formData, handleChange, errors, textFieldStyle, sectionHeaderStyle, useSize }) => (
  <PropertySection 
    formData={formData}
    handleChange={handleChange}
    errors={errors}
    textFieldStyle={textFieldStyle}
    sectionHeaderStyle={sectionHeaderStyle}
    useSize={useSize}
  />
);

// Form Additional Section Wrapper
export const FormAdditionalSection = ({ formData, handleChange, errors, textFieldStyle, sectionHeaderStyle, useSize }) => (
  <AdditionalSection 
    formData={formData}
    handleChange={handleChange}
    errors={errors}
    textFieldStyle={textFieldStyle}
    sectionHeaderStyle={sectionHeaderStyle}
    useSize={useSize}
  />
);

// Form Submit Button Section
export const FormSubmitSection = ({ submitting, useButtonSize }) => (
  <Box sx={{ mt: 3, textAlign: 'center', position: 'relative', zIndex: 2 }}>
    <Button 
      type="submit" 
      variant="contained" 
      color="primary" 
      size={useButtonSize}
      disabled={submitting}
      sx={{ 
        fontWeight: 'bold', 
        px: 4,
        py: 1.5,
        borderRadius: '4px',
        fontSize: '0.9rem'
      }}
    >
      {submitting ? (
        <>
          <CircularProgress size={20} color="inherit" sx={{ mr: 1 }} />
          SUBMITTING...
        </>
      ) : (
        'MAXIMIZE MY LISTING PROFIT NOW'
      )}
    </Button>
    <Typography sx={{ fontSize: '0.7rem', mt: 1, color: '#666' }}>
      By submitting, you agree to our Terms of Service and Privacy Policy
    </Typography>
  </Box>
);

// Form Success Message
export const FormSuccessSection = ({ resetSubmission, useButtonSize }) => (
  <Box sx={{ textAlign: 'center', py: 4, position: 'relative', zIndex: 2 }}>
    <Typography variant="h6" sx={{ color: '#2e7d32', mb: 2 }}>
      Thank You for Your Submission!
    </Typography>
    <Typography variant="body2">
      We've received your information and a member of our team will contact you shortly to discuss your flat-fee MLS listing.
    </Typography>
    <Button 
      variant="outlined" 
      color="primary"
      size={useButtonSize}
      sx={{ mt: 3 }}
      onClick={resetSubmission}
    >
      Submit Another Property
    </Button>
  </Box>
);

// Main Form Container & Logic (Orchestrates all form sections)
export const FormContainer = ({ 
  useBorder = true, 
  useColor = '#ffffff', 
  useSize = 'small', 
  useButtonSize = 'medium',
  useMiddle = false,
  showLogViewer = false,
  defaultSameAddress = false,
  sectionOrder = ['contact', 'personal', 'owner', 'property', 'additional'],
  howOptions = DEFAULT_HOW_OPTIONS,
  showBackgroundIcons = true,
  renderSections = true // Flag to render sections or let parent component handle rendering
}) => {
  const [formData, setFormData] = React.useState({
    // Contact Information
    cEmail: '',
    cPhone: '',
    cFax: '',
    cHow: howOptions[0], // Default to first option

    // Personal Information
    cBillFname: '',
    cBillLname: '',
    cBillCompany: '',
    
    // Owner Address
    cBillAddress1: '',
    cBillAddress2: '',
    cBillCity: '',
    cBillState: '',
    cBillZip: '',
    bill_county: '',
    cBillCountry: 'USA',
    
    // Same Address Toggle
    billEqualShip: defaultSameAddress ? 'Y' : 'N',
    
    // Property Information
    cShipCompany: '',
    cShipFname: '',
    cShipLname: '',
    cShipAddress1: '',
    cShipAddress2: '',
    cShipCity: '',
    cShipState: '',
    cShipZip: '',
    ship_county: '',
    cShipCountry: 'USA',
    
    // Additional Information
    cMemo: '',
    cPass: '',
    cPassHint: '',
    cWholesaleDiscount: null
  });

  // Define the background icons to use
  const backgroundIcons = [
    HomeIcon,
    PhotoCameraIcon,
    FlashOnIcon,
    AccountBalanceIcon,
    PriceCheckIcon
  ];

  const [errors, setErrors] = React.useState({});
  const { submitForm, submitting, submitSuccess, resetSubmission } = useMlsFormSubmissionComplete({
    dbHost: MLS_DB_HOST,
    dbName: MLS_DB_NAME,
    dbTable: MLS_DB_TABLE,
    dbUsername: MLS_DB_USERNAME,
    dbPassword: MLS_DB_PASSWORD
  });

  React.useEffect(() => {
    // Initialize the form with the default same address setting
    if (defaultSameAddress) {
      setFormData(prevData => ({
        ...prevData,
        billEqualShip: 'Y'
      }));
    } else {
      setFormData(prevData => ({
        ...prevData,
        billEqualShip: 'N'
      }));
    }
  }, [defaultSameAddress]);

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prevData => ({
      ...prevData,
      [name]: type === 'checkbox' ? (checked ? 'Y' : 'N') : value
    }));

    // If shipping address is same as billing, update shipping fields
    if (name === 'billEqualShip' && checked) {
      setFormData(prevData => ({
        ...prevData,
        cShipAddress1: prevData.cBillAddress1,
        cShipAddress2: prevData.cBillAddress2,
        cShipCity: prevData.cBillCity,
        cShipState: prevData.cBillState,
        cShipZip: prevData.cBillZip,
        ship_county: prevData.bill_county,
        cShipCountry: prevData.cBillCountry,
        cShipFname: prevData.cBillFname,
        cShipLname: prevData.cBillLname,
        cShipCompany: prevData.cBillCompany
      }));
    }

    // Clear error for this field if any
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  const validate = () => {
    const newErrors = {};
    
    // Required fields validation
    // Contact Information
    if (!formData.cEmail) {
      newErrors.cEmail = 'Email is required';
    } else if (!/\S+@\S+\.\S+/.test(formData.cEmail)) {
      newErrors.cEmail = 'Email is invalid';
    }
    if (!formData.cPhone) newErrors.cPhone = 'Phone number is required';
    if (!formData.cHow) newErrors.cHow = 'Please select how you heard about us';
    
    // Personal Information
    if (!formData.cBillFname) newErrors.cBillFname = 'First name is required';
    if (!formData.cBillLname) newErrors.cBillLname = 'Last name is required';
    
    // Owner Address
    if (!formData.cBillAddress1) newErrors.cBillAddress1 = 'Address is required';
    if (!formData.cBillCity) newErrors.cBillCity = 'City is required';
    if (!formData.cBillState) newErrors.cBillState = 'State is required';
    if (!formData.cBillZip) newErrors.cBillZip = 'ZIP code is required';
    
    // If not using same address for property, validate property address fields
    if (formData.billEqualShip === 'N') {
      if (!formData.cShipFname) newErrors.cShipFname = 'Property owner first name is required';
      if (!formData.cShipLname) newErrors.cShipLname = 'Property owner last name is required';
      if (!formData.cShipAddress1) newErrors.cShipAddress1 = 'Property address is required';
      if (!formData.cShipCity) newErrors.cShipCity = 'Property city is required';
      if (!formData.cShipState) newErrors.cShipState = 'Property state is required';
      if (!formData.cShipZip) newErrors.cShipZip = 'Property ZIP code is required';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    
    if (validate()) {
      console.log('Form data submitted:', formData);
      
      // Submit the form using our hook
      submitForm(formData).then(success => {
        if (success) {
          // Reset form after submission
          setFormData({
            cEmail: '',
            cPhone: '',
            cFax: '',
            cHow: howOptions[0],
            cBillFname: '',
            cBillLname: '',
            cBillCompany: '',
            cBillAddress1: '',
            cBillAddress2: '',
            cBillCity: '',
            cBillState: '',
            cBillZip: '',
            bill_county: '',
            cBillCountry: 'USA',
            billEqualShip: defaultSameAddress ? 'Y' : 'N',
            cShipCompany: '',
            cShipFname: '',
            cShipLname: '',
            cShipAddress1: '',
            cShipAddress2: '',
            cShipCity: '',
            cShipState: '',
            cShipZip: '',
            ship_county: '',
            cShipCountry: 'USA',
            cMemo: '',
            cPass: '',
            cPassHint: '',
            cWholesaleDiscount: null
          });
        }
      });
    } else {
      console.log('Form has errors:', errors);
    }
  };

  // Style configurations based on props
  const textFieldStyle = {
    backgroundColor: useColor,
    '& .MuiOutlinedInput-root': {
      '& fieldset': {
        borderColor: useBorder ? 'rgba(0, 0, 0, 0.23)' : 'transparent',
      },
    },
    marginBottom: '8px',
  };

  const formContainerStyle = {
    textAlign: useMiddle ? 'center' : 'left',
    padding: 3,
    borderRadius: 2,
    boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
    backgroundColor: '#ffffff',
    position: 'relative',
    overflow: 'hidden', // Ensure icons don't overflow the Paper
  };

  const sectionHeaderStyle = {
    fontSize: '0.9rem',
    fontWeight: 'bold',
    marginBottom: '8px',
    marginTop: '16px',
    color: 'primary.main',
    position: 'relative', // To stay above background icons
    zIndex: 2,
  };

  // Render the correct sections based on section order
  const renderFormSections = () => {
    const sectionProps = {
      formData,
      handleChange,
      errors,
      textFieldStyle,
      sectionHeaderStyle,
      useSize,
      howOptions,
    };

    return sectionOrder.map((section, index) => (
      <React.Fragment key={section}>
        {(() => {
          switch(section) {
            case 'contact':
              return <FormContactSection {...sectionProps} />;
            case 'personal':
              return <FormPersonalSection {...sectionProps} />;
            case 'owner':
              return <FormOwnerSection {...sectionProps} />;
            case 'property':
              return <FormPropertySection {...sectionProps} />;
            case 'additional':
              return <FormAdditionalSection {...sectionProps} />;
            default:
              return null;
          }
        })()}
      </React.Fragment>
    ));
  };

  // These props and functions are accessible to parent components
  const formContext = {
    formData,
    handleChange,
    errors,
    submitting,
    submitSuccess,
    resetSubmission,
    textFieldStyle,
    sectionHeaderStyle,
    useSize,
    useButtonSize,
    howOptions,
    validate,
    handleSubmit
  };

  return (
    <Paper sx={formContainerStyle} elevation={3}>
      {showLogViewer && (
        <Box sx={{ mb: 3 }}>
          <LogViewer 
            maxHeight="200px" 
            showTimestamp={true}
            showLevel={true}
            showData={true}
            maxItems={50}
          />
        </Box>
      )}
      
      {!submitSuccess ? (
        <form onSubmit={handleSubmit}>
          <FormHeaderSection />
          
          {/* Background Icons Component */}
          {showBackgroundIcons && (
            <Box sx={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', zIndex: 9999 }}>
              <SequentialBackgroundIcons 
                icons={backgroundIcons}
                opacity={0.08}
                color="#1976d2"
                maxWidth="500px"
              />
            </Box>
          )}
          
          {/* Form sections with z-index to appear above the background icons */}
          <Box sx={{ position: 'relative', zIndex: 10000 }}>
            {renderSections ? renderFormSections() : null}
          </Box>
          
          <FormSubmitSection submitting={submitting} useButtonSize={useButtonSize} />
        </form>
      ) : (
        <FormSuccessSection resetSubmission={resetSubmission} useButtonSize={useButtonSize} />
      )}
    </Paper>
  );
};

// === BENEFITS SECTION ===
export const BenefitsSection = ({ headerTextStyle, bulletPointStyle, smallTextStyle }) => (
  <>
    <Typography variant="h5" sx={{...headerTextStyle, fontSize: {xs: '1.25rem', md: '1.5rem'}}}>
      Why Choose Premier Properties For You
    </Typography>
    
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
      <Typography sx={bulletPointStyle}>
        <CheckCircleIcon sx={{ fontSize: 16, color: 'primary.main', mr: 1 }} />
        Expand Your Property's Reach: Get your MLS listing in front of active buyers' agents searching for properties like yours.
      </Typography>
      
      <Typography sx={bulletPointStyle}>
        <CheckCircleIcon sx={{ fontSize: 16, color: 'primary.main', mr: 1 }} />
        Enhance Your Visibility: Your property gets featured to qualified agents who work with Zillow, Realtor.com, and hundreds of other sites.
      </Typography>
      
      <Typography sx={bulletPointStyle}>
        <CheckCircleIcon sx={{ fontSize: 16, color: 'primary.main', mr: 1 }} />
        Access Professional Connections: Our network connects your listing with motivated buyers' agents seeking properties for their clients.
      </Typography>
      
      <Typography sx={bulletPointStyle}>
        <CheckCircleIcon sx={{ fontSize: 16, color: 'primary.main', mr: 1 }} />
        Guarantee Timely Promotion: Your property will be in front of buyers' agents within 30 days of submission.
      </Typography>
      
      <Typography sx={bulletPointStyle}>
        <CheckCircleIcon sx={{ fontSize: 16, color: 'primary.main', mr: 1 }} />
        Benefit From Proven Results: Join thousands of successful homeowners who've connected with qualified buyers through our free referral service.
      </Typography>
    </div>
    
    <Typography variant="body2" sx={{...smallTextStyle, fontWeight: 'bold'}}>
      Supercharge Your Property Visibility Today →
    </Typography>
  </>
);

// === DISCLAIMER SECTION ===
export const DisclaimerSection = ({ smallTextStyle }) => (
  <>
    <Typography variant="caption" sx={{...smallTextStyle, color: '#6c757d', fontSize: '0.65rem'}}>
      This site is not a part of the Facebook website or Facebook Inc. Additionally, This site is NOT endorsed by Facebook in any way. FACEBOOK is a trademark of FACEBOOK, Inc.
    </Typography>
    
    <Typography variant="caption" sx={{...smallTextStyle, color: '#6c757d', fontSize: '0.65rem'}}>
      INCOME DISCLAIMER: Although we make every effort to accurately represent the services and/or products presented on this website, Premier Properties For You makes no assurance, representation or promise regarding future earnings or income, or that you will make any specific amount of money, or any money at all, or that you will not lose money.
    </Typography>
    
    <Typography variant="caption" sx={{...smallTextStyle, color: '#6c757d', fontSize: '0.65rem'}}>
      © 2025 Premier Properties For You. All rights reserved.
    </Typography>
  </>
);

// Default exports for style configs
export const getDefaultStyles = (isMobile) => {
  return {
    headerTextStyle: {
      textAlign: 'center',
      fontWeight: 'bold',
      fontSize: isMobile ? '1.5rem' : '2rem',
    },
    subheaderTextStyle: {
      textAlign: 'center',
      fontSize: isMobile ? '0.9rem' : '1rem',
    },
    smallTextStyle: {
      fontSize: '0.75rem',
      textAlign: 'center',
    },
    bulletPointStyle: {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontSize: '0.75rem',
    }
  };
};

export default {
  // Major Sections
  HeroSection,
  FormContainer,
  BenefitsSection,
  DisclaimerSection,
  
  // Form Sub-Sections
  FormHeaderSection,
  FormContactSection,
  FormPersonalSection,
  FormOwnerSection,
  FormPropertySection,
  FormAdditionalSection,
  FormSubmitSection,
  FormSuccessSection,
  
  // Utilities
  getDefaultStyles
};